package com.walk.zworld.ui.fragment.video.model

import android.util.Log
import com.base.lib.base.mvvm.repository.BaseRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 通用的Repository
 * 2021-1-13.
 */
open class YouRepository : BaseRepository() {

    suspend fun getVideoList(map: MutableMap<String, Any>): YouData<PageRsp<DtDetailModel>> = request2 {
        YouRetrofitClient.service.getVideoList(map)
    }

    suspend fun getVideoDetail(map: MutableMap<String, Any>): YouData<DtDetailModel> = request2 {
        YouRetrofitClient.service.getVideoDetail(map)
    }

    suspend fun getRandomVideoList(map: MutableMap<String, Any>): YouData<List<DtDetailModel>> = request2 {
        YouRetrofitClient.service.getRandomVideoList(map)
    }


    suspend fun <T : Any> request2(call: suspend () -> YouData<T>): YouData<T> {
        return withContext(Dispatchers.IO) {
            call.invoke()
        }.apply {
            Log.d("接口返回数据----->", this.toString())
            //这儿可以对返回结果errorCode做一些特殊处理，比如token失效等，可以通过抛出异常的方式实现
            //例：当token失效时，后台返回errorCode 为 100，下面代码实现,再到baseActivity通过观察error来处理
            when (code) {
                //一般0和200是请求成功，直接返回数据
                "1000","200" -> this
                else -> throw Exception(errorMsg)
            }
        }
    }
}